package com.smart.community.commons.config.listener;

import javax.annotation.PostConstruct;

import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.smart.community.commons.dto.ApiLogDTO;
import com.smart.community.commons.mapper.SystemLogMapper;

import lombok.extern.slf4j.Slf4j;

/**
 * 监听日志主题，消费组名称自定义
 * @author Wu.Liang
 * @date 2025年7月28日
 */
@Slf4j
@Component
@RocketMQMessageListener(topic = "sc_system_log_topic", consumerGroup = "sc-system-log-group")
public class SystemLogConsumer implements RocketMQListener<String> {// selectorExpression = "system-log-tag"
	/*
	 consumerGroup = "sc-system-log-group" 是设置消费组，多个客户端只要同一个消费组，就不会产生重复消费，A拿了消息后B就拿不到了
	 还可以加标签再细分：selectorExpression = "system-log-tag"
	 */
    @Autowired
    private SystemLogMapper systemLogMapper; // MyBatis Mapper
    
    @PostConstruct
    public void init() {
    	log.info("系统操作日志消费队列初始化完毕：[sc_system_log_topic]");
    }

    @Override
    public void onMessage(String message) {
        try {
            // 1. 解析JSON消息为DTO
            ApiLogDTO logDTO = JSON.parseObject(message, ApiLogDTO.class);
            log.info("收到操作日志：{}", logDTO);
            // 2. 插入数据库（调用Mapper）
            systemLogMapper.insert(logDTO);
        } catch (Exception e) {
            // 消费失败时记录本地日志，避免消息丢失
            log.error("日志消费失败：{}", message, e);
        }
    }
}
